package com.onvifdemo.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 董光新
 * @date 2020/04/03
 */
public class TimeUtil {

    /**
     * 计算摄像机时间与系统时间是否相差30秒以内。
     * 
     * @param time
     * @return
     * @throws ParseException
     */
    @SuppressWarnings("finally")
    public static boolean timeTongBu(String time, Long systime) {
        boolean result = false;
        if (time == null) {
            return result;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置要读取的时间字符串格式
        Date date;
        try {
            date = format.parse(time);
            // 转换为Date类
            Long timestamp = date.getTime();

            System.out.println(timestamp - systime);
            // 时间相减取绝对值
            if (Math.abs(timestamp - systime) > 30000) {
                System.out.println("时间差相差30秒以上");

            } else {
                result = true;
                System.out.println("时间差相差30秒以内");
                return result;
            }

        } catch (ParseException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        } finally {
            return result;
        }

    }

    /**
     * 两个时间的差：秒
     * 
     * @param time
     * @param systime
     * @return 时间差
     */
    @SuppressWarnings("finally")
    public static long timeDiff(String time, Long systime) {
        long diff = -1;

        if (StringUtils.isEmpty(time)) {
            return diff;
        }

        if (systime <= 0) {
            return diff;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置要读取的时间字符串格式
        Date date;
        try {
            date = format.parse(time);
            // 转换为Date类
            Long timestamp = date.getTime();

            // System.out.println(timestamp - systime);
            // 时间相减取绝对值
            diff = Math.abs(timestamp - systime) / 1000;

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            diff = -1;

            e.printStackTrace();
        } finally {
            return diff;
        }

    }

    /**
     * 
     * @param dataSize
     * @return xxx秒
     */
    public static int calculationAwaitTime(int dataSize) {

        // 1000以内采用基础值60秒。
        int basicValue = 60;
        if (dataSize <= 1000) {
            return basicValue;
        }

        int rounding = dataSize / 1000;
        // 防止如5999/1000等于5，这样导致999个可能运行不完。
        rounding = rounding + 1;
        return rounding * 30;// 发现2万个速度也挺快，换成30秒的基础值
        // return rounding * 60;
    }

    public static void main(String[] args) {
        int v = calculationAwaitTime(800);
        System.out.println(v);
    }
}
